#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, os
import sqlite3
import time

class ImportFile:
    def __init__(self):
        self.conn = sqlite3.connect('data.db')
        self.cursor = self.conn.cursor()
        self.init_db()
    def init_db(self):
        self.cursor.execute('create table if not exists words (id INTEGER PRIMARY KEY NOT NULL, word varchar(30), word_explain text, learn_date init(8))')
    def save(self, word_text):
        tmp_data = word_text.split()
        word = tmp_data[0] if len(tmp_data) > 1 else word_text
        if self.check_exist(word):
            print('exist word '+word)
        else:
            tmp_data[0] = '';
            word_explain = ''.join(str(i) for i in tmp_data)
            self.cursor.execute('insert into words (id, word, word_explain) values (NULL, \''+word+'\', \''+word_explain+'\')')
    def check_exist(self,word):
        self.cursor.execute('select * from words where word = \''+word+'\'')
        return True if self.cursor.fetchall() else False
    def end(self):
        self.cursor.close()
        self.conn.commit()
        self.conn.close()
    def get_explain(self):
        self.cursor.execute('select * from words where word_explain is NULL OR word_explain = "" order by id asc')
        result = self.cursor.fetchall()
        if result:
            for item in result:
                print(item[1])
                file = os.popen('cat origin_data.txt | grep ' + item[1])
                explain = file.read()
                self.save_explain(str(item[0]), unicode(explain))
    def save_explain(self, id, word_explain):
        self.cursor.execute('update words set word_explain = ? where id = ?',[word_explain, id])

if __name__ == '__main__':
    reload(sys)
    sys.setdefaultencoding('utf8')
    if len(sys.argv) != 2:
        print("command like python import_words.py word.txt")
        exit(0)
    file_path = sys.argv[1]
    if not os.path.exists(file_path):
        print("file path error !")
        exit(0)
    importFile = ImportFile()
    # importFile.get_explain()
    with open(file_path, 'r') as f:
        for line in f.readlines():
            importFile.save(line.strip('\n'))
    importFile.end()

